package com.how2java.tmall.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.how2java.tmall.mapper.OrderitemMapper;
import com.how2java.tmall.pojo.Order;
import com.how2java.tmall.pojo.Orderitem;
import com.how2java.tmall.pojo.Product;
import com.how2java.tmall.service.OrderItemService;
import com.how2java.tmall.service.ProductService;

@Service
public class OrderItemServiceImpl implements OrderItemService{
	@Autowired
	private OrderitemMapper orderItemMapper;
	@Autowired
	private ProductService productService;
	
	@Override
	public void add(Orderitem c) {
		orderItemMapper.insertSelective(c);
	}

	@Override
	public void delete(int id) {
		orderItemMapper.deleteByPrimaryKey(id);
	}

	@Override
	public void update(Orderitem c) {
		orderItemMapper.updateByPrimaryKeySelective(c);
	}

	@Override
	public Orderitem get(int id) {
		Orderitem o = orderItemMapper.selectByPrimaryKey(id);
		setProduct(o);
		return o;
	}

	@Override
	public List<Orderitem> list() {
		return orderItemMapper.getList();
	}

	
	
	@Override
	public void fill(Order o) {
		List<Orderitem> ois =orderItemMapper.getListByOid(o.getId());
		setProduct(ois);
		
		float total = 0;
        int totalNumber = 0;
        for (Orderitem oi : ois) {
            total+=oi.getNumber()*oi.getProduct().getPromoteprice();
            totalNumber+=oi.getNumber();
        }
        o.setTotal(total);
        o.setTotalNumber(totalNumber);
        o.setOrderItems(ois);
	}

	@Override
	public void fill(List<Order> os) {
		for (Order o : os) {
            fill(o);
        }
	}
	
	public void setProduct(List<Orderitem> ois){
        for (Orderitem oi: ois) {
            setProduct(oi);
        }
    }
	
	private void setProduct(Orderitem oi) {
        Product p = productService.get(oi.getPid());
        oi.setProduct(p);
    }

	@Override
	public List<Orderitem> listByUserAndOidIsNull(int uid) {
		List<Orderitem> list = orderItemMapper.getListByUidAndOidIsNull(uid);
		setProduct(list);
		return list;
	}
}
